import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui';
import '@/assets/css/common.less';
import '@/assets/css/variable.less';
import '@/assets/css/theme/459f75/index.css';
// import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios';
import echarts from 'echarts';
require('./mock');

Vue.config.productionTip = false;
Vue.use(ElementUI, {size: 'medium'});
Vue.prototype.$axios = axios; // axios不能使用use
Vue.prototype.$elementUI = ElementUI; 
Vue.prototype.$echarts = echarts;

// 使用router.beforeEach注册一个全局前置守卫，对路由进行权限跳转
router.beforeEach((to, from, next) => {

  // 未匹配到路由时 跳转到error页面
  if (0 === to.matched.length) {

    next('/error');
    return false;
  }

  //设置axios请求头加入token
  axios.interceptors.request.use(config => {  
  if (config.push === '/') { 
  
     } else { 
		if (localStorage.getItem('token')) { 
     		//在请求头加入token，名字要和后端接收请求头的token名字一样    
   		config.headers.token=localStorage.getItem('token');        
 	 	}   
	  }  
	   return config;  
   },  
   error => { 
      return Promise.reject(error);
   });

   //响应回来token是否过期
   axios.interceptors.response.use(response => {  
  console.log('响应回来：'+response.data.code)  
    //和后端token失效返回码约定403    
    if (response.data.code == 403) {
            // 引用elementui message提示框       
            ElementUI.Message({        
                message: '身份已失效',  
                type: 'error'        
            });
            //清除token  
            localStorage.removeItem('token');
            //跳转      
            router.push('/login');    
        } else { 
                return response  
        }  
   }, 
error => { 
 return Promise.reject(error);  
 })

 router.beforeEach((to, from, next) => {
  //to到哪儿  from从哪儿离开  next跳转 为空就是放行  
    if (to.path === '/login') {
      //如果跳转为登录，就放行 
      next();    
    } else {
    //取出localStorage判断
    let token = localStorage.getItem('token');      	     
    if (token === null || token === '') { 
          console.log('请先登录')       
          next('/login');
        } else {
          next();   
        }   
  }});  

  const role = localStorage.getItem('userName');
  if (!role && to.path !== '/login') {

    next('/login');
  } else if (to.meta.permission) {

    // 如果是管理员权限则可进入，这里只是简单的模拟管理员权限而已
    role === 'admin' ? next() : next('/error');
  } else {
    // 简单的判断IE10及以下不进入富文本编辑器，该组件不兼容
    if(navigator.userAgent.indexOf('MSIE') > -1 && to.path === '/editor') {

      Vue.prototype.$alert('vue-quill-editor组件不兼容IE10及以下浏览器，请使用更高版本的浏览器查看', '浏览器不兼容通知', {
        confirmButtonText: '确定'
      });
    } else {
      next();
    }
  }
});

new Vue({
  el: '#app',
  router,
  components: {App},
  template: '<App/>'
});
